package com.zhuzhumail.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.IFEQ;
import com.zhuzhumail.dao.KqClockDao;
import com.zhuzhumail.dao.KqClockLogDao;
import com.zhuzhumail.dao.KqClockTimeDao;
import com.zhuzhumail.dao.KqEmployeeDao;
import com.zhuzhumail.entity.*;
import com.zhuzhumail.service.KqAttendanceCalendarService;
import com.zhuzhumail.utils.DateEnum;
import com.zhuzhumail.utils.KqClockUtils;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class KqAttendanceCalendarServiceImp implements KqAttendanceCalendarService {
    @Autowired
    private KqEmployeeDao kqEmployeeDao;
    @Autowired
    private KqClockDao kqClockDao;
    @Autowired
    private KqClockTimeDao kqClockTimeDao;
    @Autowired
    private KqClockLogDao kqClockLogDao;
    @Override
    public CalendarResultsVo getCalendarResultsByYear(String thirdId) {
        //查询员工的规则
        KqEmployeeEntity kqEmployeeByThirdId = kqEmployeeDao.findKqEmployeeByThirdId(thirdId);
        if (Objects.isNull(kqEmployeeByThirdId)){
            throw new RuntimeException("用户不存在");
        }
        //根据员工id查询员工的考勤规则
        List<KqClockVo> kqClockBydEpartmentId = kqClockDao.findKqClockBydEpartmentId(kqEmployeeByThirdId.getId());
        if (CollectionUtil.isNotEmpty(kqClockBydEpartmentId)){
            //不是null的时候  保证签到将今天的数据进行删除
            Iterator<KqClockVo> iterator =kqClockBydEpartmentId.iterator();
            while (iterator.hasNext()){
                //判断存在今天的进行删除就可以了
                KqClockVo next = iterator.next();
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                String s = dateFormat.format(date);
                String format = dateFormat.format(next.getAttendanceDate());
                if (format.equals(s)){
                    iterator.remove();
                }
            }
        }
        List<KqAbsenceDutyVo> kqAbsenceDutyVo=new ArrayList<>();
        //规定id不存在
        List<KqClockTimeVo> timeByRuleId=null;
        if (kqEmployeeByThirdId.getRuleId()!=null){
           timeByRuleId = kqClockTimeDao.findKqClockTimeByRuleId(kqEmployeeByThirdId.getRuleId());
          if (CollectionUtil.isNotEmpty(timeByRuleId)){
              DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
              Date date = new Date();
              String s = dateFormat.format(date);
              //获取今天的时间进行查询员工今天是不是签到了
              Date stringData = io.kqoa.modules.kq.utils.TimeUtils.convertStringData(s);
              Date leaveTime=null;
              for (int i = 0; i < timeByRuleId.size(); i++) {
                  log.info("kqClockTimeEntities.get({}).getWeekdays() == {}", i, timeByRuleId.get(i).getWeekdays());
                  //获取今天的周几
                  if (!StringUtils.isEmpty(timeByRuleId.get(i).getWeekdays())) {
                      String[] split = timeByRuleId.get(i).getWeekdays().split(";");
                      //判断今天是周几
                      int calendarWeek = DateUtil.dayOfWeekEnum(date).getValue();
                      for (int j = 0; j < split.length; j++) {
                          DateEnum dateEnum = DateEnum.getEnumByDateEnglish(split[j]);
                          if (Objects.isNull(dateEnum)) {
                              log.warn("{}，没有这个星期枚举", split[j]);
                              continue;
                          }
                          if (dateEnum.getCalendarKey() == calendarWeek) {
                              log.info("===================================");
                              //获取今天规定下班时间
                              leaveTime = timeByRuleId.get(i).getLeaveTime();
                          }
                      }
                  }
              }
              //查询签到时间
              KqClockLogEntityVo kqClockLogEntityVo = kqClockLogDao.findKqClockLogBYEmployeeIdAndAttendanceDateORDERByCreateTimeAsc(kqEmployeeByThirdId.getId(), stringData);
              KqAbsenceDutyVo  kqAbsenceDutyV=new KqAbsenceDutyVo();
              SimpleDateFormat simpleDateFormat2=new SimpleDateFormat("HH:mm");
              if (!Objects.isNull(kqClockLogEntityVo)){
                  //上班的时间
                  String format = simpleDateFormat2.format(kqClockLogEntityVo.getCreateTime());
                  kqAbsenceDutyV.setWorkTimes(format);
                  kqAbsenceDutyV.setWorkTime(stringData);
              }

              log.info("kqClockLogEntityVo == {}", JSON.toJSONString(kqClockLogEntityVo));
              log.info("leaveTime == {}", JSON.toJSONString(leaveTime));

              //没有下班时间  和 最早签到时间
              if (!Objects.isNull(kqClockLogEntityVo) && !Objects.isNull(leaveTime)) {
                  log.info("进入签到逻辑");
                  log.info("kqClockLogEntityVo === {}", JSON.toJSONString(kqClockLogEntityVo));
                  log.info("leaveTime === {}",JSON.toJSONString(leaveTime));
                  //判断到没有到规定的下班时间
                  DateFormat simpleDateFormat = DateFormat.getTimeInstance();
                  //上班的时间

                  //规定下班的时分秒
                  String format2 = simpleDateFormat.format(leaveTime);

                  //当前的时分秒
                  String format1 = simpleDateFormat.format(new Date());
                  //第2个大于第一个 返回1
                  Integer seconds = io.kqoa.modules.kq.utils.TimeUtils.compareHoursMinutesSeconds(format2,format1);
                  if (seconds==1){
                      //下班
                      KqClockLogEntityVo kqClockLogEntity = kqClockLogDao.findKqClockLogBYEmployeeIdAndAttendanceDateORDERByCreateTimeDESC(kqEmployeeByThirdId.getId(), stringData);
                      //下班时间
                      if (!Objects.isNull(kqClockLogEntity)){
                          DateFormat simpleDateForm = DateFormat.getTimeInstance();
                          String format22 = simpleDateFormat2.format(kqClockLogEntity.getCreateTime());
                          kqAbsenceDutyV.setLeaveTime(format22);
                      }
                  }
                  //月份
                  kqAbsenceDutyV.setMonth(io.kqoa.modules.kq.utils.TimeUtils.queryMonthAcquisitionTime(stringData));
                  kqAbsenceDutyV.setAbsenceStatus("签到");
                  //规定下班的时间

                  log.info("签到数据,{}",kqAbsenceDutyVo.toString());
                  kqAbsenceDutyVo.add(kqAbsenceDutyV);
              }
          }
        }

        if ((CollectionUtils.isEmpty(kqAbsenceDutyVo)&&kqEmployeeByThirdId.getRuleId()!=null) || CollectionUtils.isEmpty(kqClockBydEpartmentId)&&CollectionUtils.isEmpty(kqAbsenceDutyVo)){
            log.info("没有规则id");
            List<AttendanceCalendarVo> attendanceCalendarVos = KqClockUtils.queryAllAbsenceStatusUtils();
            CalendarResultsVo calendarResultsVo=new  CalendarResultsVo();
            calendarResultsVo.setFirstMonth(attendanceCalendarVos.get(0));
            calendarResultsVo.setTheSecondMonth(attendanceCalendarVos.get(1));
            calendarResultsVo.setTheThirdMonth(attendanceCalendarVos.get(2));
            return calendarResultsVo;
        }
        log.info("遍历考勤日志数据");

        kqClockBydEpartmentId.stream().forEach(kqClockEntity -> {
            log.info("员工的考勤日志",kqClockEntity.toString());
            KqAbsenceDutyVo kqAbsenceDuty = new KqAbsenceDutyVo();
            if (kqClockEntity.getReviewStatus()==1){
                kqAbsenceDuty.setAbsenceStatus("已维护");
            }else {
                kqAbsenceDuty.setAbsenceStatus("缺勤");
            }
            if (!Objects.isNull(kqClockEntity.getLeaveTime())&&!Objects.isNull(kqClockEntity.getWorkTime())) {
                if (kqClockEntity.getReviewStatus()==1){
                    kqAbsenceDuty.setWorkTime(kqClockEntity.getAttendanceDate());
                    //获取考勤时间的月份
                    kqAbsenceDuty.setMonth(io.kqoa.modules.kq.utils.TimeUtils.queryMonthAcquisitionTime(kqClockEntity.getAttendanceDate()));
                }else {
                    //计算缺勤的时间
                    Integer KqClocktime = Math.round((kqClockEntity.getLeaveTime().getTime()-kqClockEntity.getWorkTime().getTime())/1000/60/60);
                    log.info("计算的缺勤的时间",Integer.toString(KqClocktime));
                    kqAbsenceDuty.setAbsenceTime(KqClocktime);
                    kqAbsenceDuty.setWorkTime(kqClockEntity.getAttendanceDate());
                    //获取考勤时间的月份
                    kqAbsenceDuty.setMonth(io.kqoa.modules.kq.utils.TimeUtils.queryMonthAcquisitionTime(kqClockEntity.getAttendanceDate()));

                }
                kqAbsenceDutyVo.add(kqAbsenceDuty);
            }

        });


        return null;
    }
}
